package com.stylefeng.guns.modular.train.controller;

import com.alibaba.fastjson.JSON;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.system.service.impl.QualityGradeRuleServiceImpl;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.train.service.IExpertTalentsPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 专家人才积分控制器
 *
 * @author fengshuonan
 * @Date 2018-01-28 18:55:58
 */
@Controller
@RequestMapping("/expertTalentsPoints")
public class ExpertTalentsPointsController extends BaseController {

    private String PREFIX = "/train/expertTalentsPoints/";

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IExpertTalentsPointsService expertTalentsPointsService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;

    @Resource
    IDictService dictService;

    private static List<ExpertTalentsPoints> REPEAT = new ArrayList<>();
    /**
     * 跳转到专家人才积分首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "expertTalentsPoints.html";
    }

    /**
     * 跳转到添加专家人才积分
     */
    @RequestMapping("/expertTalentsPoints_add")
    public String expertTalentsPointsAdd(Model model) {
        List<Dict> expertTypes = dictService.getChildByCode(Const.DICT_EXPERT);
        // TODO: 2018/1/28 修改const
        model.addAttribute("levels", expertTypes);
        model.addAttribute("evaluationResults", dictService.getByPCode("evaluation_result"));
        return PREFIX + "expertTalentsPoints_add.html";
    }

    /**
     * 跳转到修改专家人才积分
     */
    @RequestMapping("/expertTalentsPoints_update/{expertTalentsPointsId}")
    public String expertTalentsPointsUpdate(@PathVariable String expertTalentsPointsId, Model model) {
        ExpertTalentsPoints expertTalentsPoints = expertTalentsPointsService.selectById(expertTalentsPointsId);
        model.addAttribute("item",expertTalentsPoints);
        // TODO: 2018/1/28 修改const
        model.addAttribute("levels", dictService.getChildByCode(Const.DICT_EXPERT));

        model.addAttribute("personnalTitles", qualityGradeRuleService.getByGradeType(expertTalentsPoints.getLevelCode()));
        model.addAttribute("evaluationResults", dictService.getByPCode("evaluation_result"));
        LogObjectHolder.me().set(expertTalentsPoints);
        return PREFIX + "expertTalentsPoints_edit.html";
    }

    /**
     * 获取专家人才积分列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            List<ExpertTalentsPoints> expertTalentsPointss = expertTalentsPointsService.selectList(null);
            expertTalentsPointss.forEach(t -> {
                if(t.getEngageDate() != null){
                    t.setStrEngageDate(Const.df.format(t.getEngageDate()));
                }
            });
            return expertTalentsPointss;
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<ExpertTalentsPoints> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<ExpertTalentsPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            list = expertTalentsPointsService.selectList(nwWrapper);
        }
        list.forEach(t -> {
            if(t.getEngageDate() != null){
                t.setStrEngageDate(Const.df.format(t.getEngageDate()));
            }
        });
        return list;
    }
    /**
     * 新增专家人才积分
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ExpertTalentsPoints expertTalentsPoints) {
        expertTalentsPointsService.insert(expertTalentsPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody ExpertTalentsPoints[] repeatData) {
        List<ExpertTalentsPoints> expertTalentsPointss = Arrays.asList(repeatData);
        Date now = new Date();

        Map<String, String> expertMap = dictService.getMapNameCodeByPcode(Const.DICT_EXPERT);
        Map<String,List<QualityGradeRule>> titles = new HashMap<>();
        for (String key : expertMap.keySet()) {
            String code = expertMap.get(key);
            List<QualityGradeRule> t = qualityGradeRuleService.getByGradeType(code);
            titles.put(code,t);
        }

        expertTalentsPointss.forEach(expertTalentsPoints -> {
            expertTalentsPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
            expertTalentsPoints.setCreateDate(now);

            //转级别
            String levelType = expertMap.get(expertTalentsPoints.getLevel().trim());
            expertTalentsPoints.setLevelCode(levelType);

            //转人才称号
            List<QualityGradeRule> qualityGradeRules = titles.get(expertTalentsPoints.getLevelCode());
            for (QualityGradeRule qualityGradeRule : qualityGradeRules) {
                if(qualityGradeRule.getGrade().equals(expertTalentsPoints.getPersonnalTitle().trim())){
                    expertTalentsPoints.setPersonnalTitleCode(qualityGradeRule.getGradeCode());
                    expertTalentsPoints.setIntegral(qualityGradeRule.getIntegral());
                    break;
                }else {
                    expertTalentsPoints.setIntegral(0.0);
                }
            }

        });
        expertTalentsPointsService.insertBatch(expertTalentsPointss);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除专家人才积分
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String expertTalentsPointsId) {
        if(expertTalentsPointsId.contains(",")){
            List<String> ids = Arrays.asList(expertTalentsPointsId.split(","));
            expertTalentsPointsService.deleteBatchIds(ids);
        }else{
            expertTalentsPointsService.deleteById(expertTalentsPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改专家人才积分
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ExpertTalentsPoints expertTalentsPoints) {
        expertTalentsPointsService.updateById(expertTalentsPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * 专家人才积分详情
     */
    @RequestMapping(value = "/detail/{expertTalentsPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("expertTalentsPointsId") String expertTalentsPointsId) {
        return expertTalentsPointsService.selectById(expertTalentsPointsId);
    }


    /**
     * 跳转到导入专家人才积分
     */
    @RequestMapping("/expertTalentsPoints_import")
    public String expertTalentsPointsImport() {
        return PREFIX + "expertTalentsPoints_import.html";
    }

    @RequestMapping("/type/qualityGradeRule")
    @ResponseBody
    public MvcResult getWinLevelRule(String levelCode){
        List<QualityGradeRule> personnalTitles = qualityGradeRuleService.getByGradeType(levelCode);
        MvcResult mvcResult = new MvcResult();
        mvcResult.setData(personnalTitles);
        return mvcResult;
    }

    /**
     * 导入专家人才积分
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);
        int count =2;
        try {
            List<ExpertTalentsPoints> expertTalentsPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), ExpertTalentsPoints.class, params);
            Date now = new Date();

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<ExpertTalentsPoints> noRepeat = new ArrayList<>();
            List<ExpertTalentsPoints> hasNameList = new ArrayList<>();

            Map<String, String> expertMap = dictService.getMapNameCodeByPcode(Const.DICT_EXPERT);
            Map<String,List<QualityGradeRule>> titles = new HashMap<>();
            for (String key : expertMap.keySet()) {
                String code = expertMap.get(key);
                List<QualityGradeRule> t = qualityGradeRuleService.getByGradeType(code);
                titles.put(code,t);
            }

            for (ExpertTalentsPoints expertTalentsPoints : expertTalentsPointss) {
                expertTalentsPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                expertTalentsPoints.setCreateDate(now);

                if(StringUtils.isEmpty(expertTalentsPoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(expertTalentsPoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(expertTalentsPoints.getEmpName()).contains(",")) {
                            //有重名情况
                            expertTalentsPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(expertTalentsPoints);
                        } else {
                            //无重名、正常插入
                            expertTalentsPoints.setEmpCode(nameAndCode.get(expertTalentsPoints.getEmpName()));

                            //转级别
                            String levelType = expertMap.get(expertTalentsPoints.getLevel().trim());
                            expertTalentsPoints.setLevelCode(levelType);

                            //转人才称号
                            List<QualityGradeRule> qualityGradeRules = titles.get(expertTalentsPoints.getLevelCode());
                            for (QualityGradeRule qualityGradeRule : qualityGradeRules) {
                                if(qualityGradeRule.getGrade().equals(expertTalentsPoints.getPersonnalTitle().trim())){
                                    expertTalentsPoints.setPersonnalTitleCode(qualityGradeRule.getGradeCode());
                                    expertTalentsPoints.setIntegral(qualityGradeRule.getIntegral());
                                    break;
                                }else {
                                    expertTalentsPoints.setIntegral(0.0);
                                }
                            }

                            noRepeat.add(expertTalentsPoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + expertTalentsPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    //转级别
                    String levelType = expertMap.get(expertTalentsPoints.getLevel().trim());
                    expertTalentsPoints.setLevelCode(levelType);

                    //转人才称号
                    List<QualityGradeRule> qualityGradeRules = titles.get(expertTalentsPoints.getLevelCode());
                    for (QualityGradeRule qualityGradeRule : qualityGradeRules) {
                        if(qualityGradeRule.getGrade().equals(expertTalentsPoints.getPersonnalTitle().trim())){
                            expertTalentsPoints.setPersonnalTitleCode(qualityGradeRule.getGradeCode());
                            expertTalentsPoints.setIntegral(qualityGradeRule.getIntegral());
                            break;
                        }else {
                            expertTalentsPoints.setIntegral(0.0);
                        }
                    }

                    hasNameList.add(expertTalentsPoints);
                }

                count++;
            }

        //不重复，先插入
            if(noRepeat.size() > 0){
                expertTalentsPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                expertTalentsPointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<ExpertTalentsPoints> expertTalentsPoints= expertTalentsPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("专家人才积分统计表", "专家人才积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ExpertTalentsPoints.class, expertTalentsPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="专家人才积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
